package org.jetnuke.servlets.listeners;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.common.RequestListener;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.RefererDAO;
import org.jetnuke.entities.MainConfig;
import org.jetnuke.entities.Referer;
import org.jetnuke.servlets.utilities.StringUtils;


public class RefererListener implements RequestListener {
	private final static Logger s_log = Logger.getLogger(RefererListener.class);
	public static Pattern ptUnknown=Pattern.compile("^unknown", Pattern.CASE_INSENSITIVE);
	public static Pattern ptBookmark=Pattern.compile("^bookmark", Pattern.CASE_INSENSITIVE);
	public static Pattern ptLocalhost=Pattern.compile("localhost", Pattern.CASE_INSENSITIVE);
	/* (non-Javadoc)
	 * @see org.jetnuke.common.RequestListener#request(javax.servlet.http.HttpServletRequest, org.apache.velocity.VelocityContext, org.jetnuke.common.IUserInfo, org.jetnuke.common.IAdminInfo, boolean, long)
	 */
	public void request(HttpServletRequest request, VelocityContext vc, IUserInfo iUserInfo, IAdminInfo iAdminInfo, boolean isIndex, long time) {
		MainConfig config=(MainConfig)request.getAttribute("MAIN_CONFIG");
		if(config.getHTTPREF()==0)
			return;
		String referer_=request.getHeader("Referer");
		if(referer_==null)
			return;
		referer_=StringUtils.removeHtml(referer_);
		
		String nukeUrl=config.getNUKEURL();
		int length=nukeUrl.length();
		if(referer_.length()>=length){
			if(referer_.substring(0,length).equalsIgnoreCase(nukeUrl))
				return;
		}
		if(referer_==null)
			return;
		referer_=referer_.trim();
		if(validReferer(referer_)){
			Referer ref=new Referer();
			ref.setURL(referer_);
			RefererDAO rm=DataAccessDriver.getInst().newRefererDAO();
			try {
				rm.addNew(ref);
				
				if(rm.countAll()>config.getHTTPREFMAX()){
					
					rm.deleteAll();
					
				};
			} catch (Exception e) {
				s_log.error(e);
			}
		}
		
	}
	private static boolean validReferer(String referer_){
		return !referer_.equals("")&& !ptLocalhost.matcher(referer_).find()&& !ptUnknown.matcher(referer_).find()&& !ptBookmark.matcher(referer_).find();
	}
	static public void main(String args[]){
		String referer_="http://localhost";
		System.out.println(validReferer(referer_));
	}

}
